package postgres

import (
	"auth/model"
	"auth/model/entity"
)

var Api = &api{}

type api struct{}

func (a *api) Create(m *entity.Api) (int64, error) {
	err := db.Create(m).Error
	return m.ID, err
}

func (a *api) Find(id int64) (*entity.Api, error) {
	e := &entity.Api{}
	err := db.Model(&entity.Api{}).Find(&e, id).Error
	return e, err
}

func (a *api) GetAllApis() (apis []*entity.Api, err error) {
	err = db.Model(&entity.Api{}).Find(&apis).Error
	return
}

func (a *api) FindByParameter(in *model.ApiInfo) (*entity.Api, error) {
	var (
		err error
		q   = db.Model(&entity.Api{})
		e   *entity.Api
	)
	if in.Path != "" {
		q = q.Where("path = ?", in.Path)
	}
	if in.Method != "" {
		q = q.Where("method = ?", in.Method)
	}
	err = q.First(&e).Error
	return e, err
}

func (a *api) Update(id int64, dict map[string]interface{}) error {
	return db.Model(&entity.Api{}).Where("id = ?", id).Updates(dict).Error
}

func (a *api) Delete(id int64) error {
	return db.Delete(&entity.Api{}, id).Error
}

func (a *api) List(in *model.ApiListRequest) (int, []*entity.Api, error) {
	var (
		q     = db.Model(&entity.Api{})
		err   error
		total int64
		apis  []*entity.Api
	)

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&apis).Error; err != nil {
		return 0, nil, err
	}
	return int(total), apis, err
}
